<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const activeTab = ref('realtime')
const dateRange = ref([])
const tempChartRef = ref(null)
const humidityChartRef = ref(null)
const gasChartRef = ref(null)
const noiseChartRef = ref(null)

let tempChart = null
let humidityChart = null
let gasChart = null
let noiseChart = null
let timer = null

const sensorData = ref({
  temperature: [],
  humidity: [],
  gas: [],
  noise: []
})

// 初始化图表
const initCharts = () => {
  // 温度图表
  tempChart = echarts.init(tempChartRef.value)
  const tempOption = {
    title: {
      text: '温度实时监控',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '温度(°C)',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '温度',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#F56C6C'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(245, 108, 108, 0.3)' },
          { offset: 1, color: 'rgba(245, 108, 108, 0)' }
        ])
      }
    }]
  }
  tempChart.setOption(tempOption)

  // 湿度图表
  humidityChart = echarts.init(humidityChartRef.value)
  const humidityOption = {
    title: {
      text: '湿度实时监控',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '湿度(%)',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '湿度',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0)' }
        ])
      }
    }]
  }
  humidityChart.setOption(humidityOption)

  // 气体浓度图表
  gasChart = echarts.init(gasChartRef.value)
  const gasOption = {
    title: {
      text: '气体浓度监控',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '浓度(ppm)',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '气体浓度',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#E6A23C'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
          { offset: 1, color: 'rgba(230, 162, 60, 0)' }
        ])
      }
    }]
  }
  gasChart.setOption(gasOption)

  // 噪音图表
  noiseChart = echarts.init(noiseChartRef.value)
  const noiseOption = {
    title: {
      text: '噪音监控',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '分贝(dB)',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '噪音',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#67C23A'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
          { offset: 1, color: 'rgba(103, 194, 58, 0)' }
        ])
      }
    }]
  }
  noiseChart.setOption(noiseOption)
}

// 更新实时数据
const updateRealTimeData = () => {
  const now = new Date()
  const newData = {
    time: now.getTime(),
    temperature: Math.random() * 10 + 20,
    humidity: Math.random() * 20 + 50,
    gas: Math.random() * 100,
    noise: Math.random() * 30 + 40
  }

  // 更新各图表数据
  tempChart.series[0].data.push([newData.time, newData.temperature])
  humidityChart.series[0].data.push([newData.time, newData.humidity])
  gasChart.series[0].data.push([newData.time, newData.gas])
  noiseChart.series[0].data.push([newData.time, newData.noise])

  // 保持最近30个数据点
  if (tempChart.series[0].data.length > 30) {
    tempChart.series[0].data.shift()
    humidityChart.series[0].data.shift()
    gasChart.series[0].data.shift()
    noiseChart.series[0].data.shift()
  }

  // 更新图表
  tempChart.setOption({ series: [{ data: tempChart.series[0].data }] })
  humidityChart.setOption({ series: [{ data: humidityChart.series[0].data }] })
  gasChart.setOption({ series: [{ data: gasChart.series[0].data }] })
  noiseChart.setOption({ series: [{ data: noiseChart.series[0].data }] })
}

// 查询历史数据
const queryHistory = () => {
  console.log('查询历史数据:', dateRange.value)
  // 这里添加查询历史数据的逻辑
}

// 窗口大小改变时重置图表大小
const handleResize = () => {
  tempChart?.resize()
  humidityChart?.resize()
  gasChart?.resize()
  noiseChart?.resize()
}

onMounted(() => {
  initCharts()
  // 每秒更新数据
  timer = setInterval(updateRealTimeData, 1000)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  window.removeEventListener('resize', handleResize)
  tempChart?.dispose()
  humidityChart?.dispose()
  gasChart?.dispose()
  noiseChart?.dispose()
})
</script>

<template>
  <div class="sensor-monitor">
    <el-tabs v-model="activeTab" class="monitor-tabs">
      <!-- 实时监控 -->
      <el-tab-pane label="实时监控" name="realtime">
        <div class="monitor-header">
          <h2>实时数据监控</h2>
          <div class="monitor-info">
            <el-tag type="success">数据更新频率: 1秒/次</el-tag>
            <el-tag type="info">保留最近30条数据</el-tag>
          </div>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div class="chart-container" ref="tempChartRef"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div class="chart-container" ref="humidityChartRef"></div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="mt-4">
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div class="chart-container" ref="gasChartRef"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div class="chart-container" ref="noiseChartRef"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 历史数据 -->
      <el-tab-pane label="历史数据" name="history">
        <div class="history-header">
          <h2>历史数据查询</h2>
          <el-form inline>
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="[
                  new Date(2000, 1, 1, 0, 0, 0),
                  new Date(2000, 1, 1, 23, 59, 59),
                ]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="queryHistory">查询</el-button>
              <el-button>导出数据</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="hover" class="history-chart">
          <div class="chart-container" ref="historyChart"></div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.sensor-monitor {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

.monitor-tabs {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.monitor-header,
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.monitor-header h2,
.history-header h2 {
  margin: 0;
  color: #303133;
}

.monitor-info {
  display: flex;
  gap: 10px;
}

.chart-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.chart-card:hover {
  transform: translateY(-5px);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.mt-4 {
  margin-top: 20px;
}

.history-chart {
  margin-top: 20px;
}

.history-chart .chart-container {
  height: 500px;
}
</style>